想像原始資料如同未標記的資料流——一片記憶體的荒野。在 Rust 中,我們首先以「連續區塊」來處理資料 連續區塊 (切片與陣列)。這種從原始資料轉向定義資料結構的過程,標誌著從匿名記憶體到 有意義的結構。
1. 「原始」層級
切片與陣列以最簡化的形式呈現資料。安全性透過 編譯時期的所有權檢查 而非執行時期的額外負荷來維持。使用借用(&)讓我們能在不移動值的情況下,建立對資料的「視角」。
2. 語意上的限制
雖然像 first_word 這樣的函數具有彈性(可接受 String、 &str或字面常數),但會遇到語意上的限制。編譯器知道記憶體是安全的,卻不知道資料所代表的意義 所代表的內容 (例如使用者名稱與感測器讀值之間的差異)直到我們將其映射至一個 Struct。
架構原則: 所有權、借用與切片的概念確保了 Rust 程式在編譯時期的記憶體安全,無需垃圾回收機制。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What is the main benefit of using a string slice (&str) over a String in a function signature?
It takes ownership of the data to prevent leaks.
It allows the function to accept both Strings and string literals via deref coercion.
It automatically converts the text to uppercase.
It stores the data on the stack instead of the heap.
✅ Correct!
Correct! Using &str makes the API more flexible as it can view data owned by Strings or literals.❌ Incorrect
Slices do not take ownership; they are borrowed views.QUESTION 2
In the expression 'let slice = &a[1..3]', what indices of array 'a' are included?
1, 2, and 3
1 and 2
2 and 3
Only index 1
✅ Correct!
Rust range syntax [n..m] is inclusive of the start and exclusive of the end.❌ Incorrect
The range [1..3] includes index 1 and 2, but excludes 3.QUESTION 3
Why do we say raw slices lack 'domain clarity'?
They are technically unsafe to use in production.
They don't provide metadata about what the data represents in the business logic.
They cannot be used with integers.
They are limited to 256 bytes of data.
✅ Correct!
Correct. A &[u8] could be a file, an image, or a name; only a Struct provides the semantic name.❌ Incorrect
Slices are memory-safe, but they are 'anonymous' chunks of data.QUESTION 4
Does a slice (&[i32]) own the data it points to?
Yes, it takes ownership of the range.
No, it is a reference to a portion of data owned by another variable.
Only if the array is mutable.
Yes, but only at compile time.
✅ Correct!
Slices are inherently borrows. They must not outlive the data they point to.❌ Incorrect
If a slice owned data, it would be a Vector or an Array, not a slice.QUESTION 5
When does Rust check for slice out-of-bounds errors?
Exclusively at compile time.
Exclusively at runtime.
Compile time for fixed ranges; runtime for dynamic indices.
Rust does not check for bounds errors.
✅ Correct!
Rust uses a mix of compile-time analysis and runtime checks to ensure memory safety.❌ Incorrect
Rust is famous for preventing buffer overflows through strict checking.Case Study: Sensor Data Streaming
Transitioning from Raw Slices to Domain Structs
You are processing a stream of temperature readings from an IoT device. Initially, you handle the data as a raw slice `&[f64]`. You need to ensure the logic is safe and then refactor for clarity.
Q
1. Why might using `&[f64]` lead to bugs in a large team project compared to a named Struct?
Solution:
A raw slice like `&[f64]` lacks context. Without a schema, a developer might confuse a slice of 'temperatures' with a slice of 'humidity' or 'timestamps,' as both share the same underlying type.
A raw slice like `&[f64]` lacks context. Without a schema, a developer might confuse a slice of 'temperatures' with a slice of 'humidity' or 'timestamps,' as both share the same underlying type.
Q
2. If you create a slice `let window = &readings[0..10]`, what happens if the `readings` vector is cleared?
Solution:
The Rust compiler will throw an error. The slice `window` borrows `readings`, so `readings` cannot be modified (cleared) while the slice is still in use, preventing a dangling pointer.
The Rust compiler will throw an error. The slice `window` borrows `readings`, so `readings` cannot be modified (cleared) while the slice is still in use, preventing a dangling pointer.
Q
3. How does the 'first_word' pattern apply to this sensor data?
Solution:
Just as `first_word` identifies a delimiter in a string, you could write a function that finds the first 'out-of-range' reading in a slice. It processes raw data flexibly without needing to own the entire dataset.
Just as `first_word` identifies a delimiter in a string, you could write a function that finds the first 'out-of-range' reading in a slice. It processes raw data flexibly without needing to own the entire dataset.